package com.foreverwin.mes.lims.controller;

import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.model.DefeRecodesOfWorkInProc;
import com.foreverwin.mes.lims.service.DefeRecodesOfWorkInProcService;
import com.foreverwin.mes.lims.util.NowString;
import com.foreverwin.mes.meapi.model.Resrce;
import com.foreverwin.mes.meapi.service.ResrceService;
import com.foreverwin.mes.production.dto.SfcInWorkDto;
import com.foreverwin.mes.production.service.SfcExService;
import com.sap.me.frame.domain.BusinessException;
import com.sap.me.nonconformance.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.sap.me.extension.Services;

/**
 *
 * @author Mark
 * @since 2020-02-17
 */
@Controller
@RequestMapping("/defeRecodesOfWorkInProcs")
public class DefeRecodesOfWorkInProcController {
    private final Logger logger = LoggerFactory.getLogger(DefeRecodesOfWorkInProcController.class);
    private final Boolean isLocalTest = false; //是否在本地测试（若为true，返回自定义数据）

    @Autowired
    public DefeRecodesOfWorkInProcService defeRecodesOfWorkInProcService;

    @Autowired
    private SfcExService sfcExService;

    @Autowired
    private ResrceService resrceService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getDefeRecodesOfWorkInProcById(@PathVariable String id) {
        DefeRecodesOfWorkInProc result;
        try {
            result = defeRecodesOfWorkInProcService.selectById(id);
        } catch (Exception e) {
            logger.error("getDefeRecodesOfWorkInProcById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getDefeRecodesOfWorkInProcList(DefeRecodesOfWorkInProc defeRecodesOfWorkInProc){
        List<DefeRecodesOfWorkInProc> result;
        try {
            EntityWrapper<DefeRecodesOfWorkInProc> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(defeRecodesOfWorkInProc);
            result = defeRecodesOfWorkInProcService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getDefeRecodesOfWorkInProcList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getDefeRecodesOfWorkInProcPageList")
    public AjaxResult getDefeRecodesOfWorkInProcPageList(FrontPage<DefeRecodesOfWorkInProc> frontPage, DefeRecodesOfWorkInProc defeRecodesOfWorkInProc){
        Page result;
        try {
            String site = CommonMethods.getSite();
            defeRecodesOfWorkInProc.setSite(site);
            EntityWrapper<DefeRecodesOfWorkInProc> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(defeRecodesOfWorkInProc);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("resource", frontPage.getGlobalQuery())
                    .or().like("resoDesc", frontPage.getGlobalQuery())
                    .or().like("operation", frontPage.getGlobalQuery())
                    .or().like("sfcBatch", frontPage.getGlobalQuery())
                    .or().like("product", frontPage.getGlobalQuery())
                    .or().like("measUnit", frontPage.getGlobalQuery())
                    .or().like("defectCode", frontPage.getGlobalQuery())
                    .or().like("defectDesc", frontPage.getGlobalQuery())
                    .or().like("determineResult", frontPage.getGlobalQuery())
                    .or().like("remark", frontPage.getGlobalQuery())
                    .or().like("creator", frontPage.getGlobalQuery())
                    .or().like("updater", frontPage.getGlobalQuery())
        ;
            }
            result = defeRecodesOfWorkInProcService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getDefeRecodesOfWorkInProcPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param defeRecodesOfWorkInProc  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult defeRecodesOfWorkInProcSave(@RequestBody DefeRecodesOfWorkInProc defeRecodesOfWorkInProc) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        Date nowTime = new Date();
        //------------------本地测试数据开始------------------------------------------------------------------------------------
        if(isLocalTest) {
            user = "mark";
        }
        //------------------本地测试数据结束------------------------------------------------------------------------------------
        int count;
        //------------------------------------------------------------------------------------------------------------
        String resource = defeRecodesOfWorkInProc.getResource();
        String sfcBatch = defeRecodesOfWorkInProc.getSfcBatch();
        String handle = HandleEnum.DEFECTIVE_RECORDS_OF_WIP.getHandle( site, resource, sfcBatch);
        //------------------------------------------------------------------------------------------------------------
        DefeRecodesOfWorkInProc oldIns = defeRecodesOfWorkInProcService.selectById(handle);
        if(oldIns==null){
            //----------------------------Insert-------------------------------------------------------------------
            defeRecodesOfWorkInProc.setHandle(handle);
            defeRecodesOfWorkInProc.setSite(site);
            defeRecodesOfWorkInProc.setCreator(user);
            defeRecodesOfWorkInProc.setUpdater(user);
            defeRecodesOfWorkInProc.setCreatedDateTime(nowTime);
            defeRecodesOfWorkInProc.setModifiedDateTime(nowTime);
            try {
                count = defeRecodesOfWorkInProcService.insert(defeRecodesOfWorkInProc) ? 1 : 0;
            } catch (Exception e) {
                logger.error("defeRecodesOfWorkInProcSave -=- {}", e.toString());
                return AjaxResult.error( e.getMessage() );
            }
            return AjaxResult.success(count == 0 ? null : defeRecodesOfWorkInProc);
        }else{
            //----------------------------Update-------------------------------------------------------------------
            oldIns.setResoDesc(defeRecodesOfWorkInProc.getResoDesc());
            oldIns.setOperation(defeRecodesOfWorkInProc.getOperation());
            oldIns.setProduct(defeRecodesOfWorkInProc.getProduct());
            oldIns.setMeasUnit(defeRecodesOfWorkInProc.getMeasUnit());
            oldIns.setDefectCode(defeRecodesOfWorkInProc.getDefectCode());
            oldIns.setDefectDesc(defeRecodesOfWorkInProc.getDefectDesc());
            oldIns.setDetermineResult(defeRecodesOfWorkInProc.getDetermineResult());
            oldIns.setRemark(defeRecodesOfWorkInProc.getRemark());
            oldIns.setUpdater(user);
            oldIns.setModifiedDateTime(nowTime);
            try {
                count = defeRecodesOfWorkInProcService.updateAllColumnById(oldIns) ? 1 : 0;
            } catch (Exception e) {
                logger.error("defeRecodesOfWorkInProcSave -=- {}", e.toString());
                return AjaxResult.error( e.getMessage() );
            }
            return AjaxResult.success(count == 0 ? null : defeRecodesOfWorkInProc);
        }



    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult defeRecodesOfWorkInProcDelete(@PathVariable("id") String id){
        int count;
        try {
            count = defeRecodesOfWorkInProcService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("defeRecodesOfWorkInProcDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = defeRecodesOfWorkInProcService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("defeRecodesOfWorkInProcBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * （在制不良录入）通过site查询：设备、设备描述、工序
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getResourceAndOperation")
    public AjaxResult getResourceAndOperation(DefeRecodesOfWorkInProc defeRecodesOfWorkInProc){
        String site = CommonMethods.getSite();
        defeRecodesOfWorkInProc.setSite(site);
        ArrayList<DefeRecodesOfWorkInProc> result = new ArrayList<DefeRecodesOfWorkInProc>();
        List<Resrce> result_r;
        try {
            Resrce resrce_select = new Resrce();
            EntityWrapper<Resrce> EntityWrapper = new EntityWrapper<>();
            resrce_select.setSite(CommonMethods.getSite());
            EntityWrapper.setEntity(resrce_select);
            result_r = resrceService.selectList(EntityWrapper);
            for(Resrce resrce:result_r){
                DefeRecodesOfWorkInProc ins = new DefeRecodesOfWorkInProc();
                if( resrce.getOperationBo()==null || "".equalsIgnoreCase(resrce.getOperationBo()) ){
                    continue;
                }
                ins.setResource(resrce.getResrce());
                ins.setResoDesc(resrce.getDescription());
                ins.setOperation(StringUtils.trimHandle(resrce.getOperationBo()));
                result.add(ins);
            }

        } catch (Exception e) {
            logger.error("getResourceAndOperation -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * （在制不良录入）查询：不良代码
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getNCCode")
    public AjaxResult getNCCode(DefeRecodesOfWorkInProc defeRecodesOfWorkInProc) throws BusinessException {
        ArrayList<DefeRecodesOfWorkInProc> result = new ArrayList<DefeRecodesOfWorkInProc>();
        String site = CommonMethods.getSite();
        //----------------本地测试Start-----------------------------------------------------------------------------------------------
        if(isLocalTest) {
            for (int i = 0; i < 4; i++) {
                DefeRecodesOfWorkInProc defeRecodesOfWorkInProcIns = new DefeRecodesOfWorkInProc();
                defeRecodesOfWorkInProcIns.setDefectCode("WG01-NG" + i);
                defeRecodesOfWorkInProcIns.setDefectDesc("外观不良" + i);
                result.add(defeRecodesOfWorkInProcIns);
            }
            return AjaxResult.success(result);
        }
        //----------------本地测试End-----------------------------------------------------------------------------------------------
        String operation = defeRecodesOfWorkInProc.getOperation();
        String operation_handle = HandleEnum.OPERATION.getHandle( site, operation, "#");
        NCProductionServiceInterface ncProductionService = Services.getService("com.sap.me.nonconformance","NCProductionService",site);
        FindValidNCGroupsAndCodesRequest findValidNCGroupsAndCodesRequest = new FindValidNCGroupsAndCodesRequest();
        findValidNCGroupsAndCodesRequest.setOperationRef(operation_handle);
        FindValidNCGroupsAndCodesResponse findValidNCGroupsAndCodesResponse = ncProductionService.findValidNCGroupsAndCodes(findValidNCGroupsAndCodesRequest);
        List<NCGroupAndCodesSummary> ncGroupsAndCodesL = findValidNCGroupsAndCodesResponse.getNcGroupsAndCodes();
        for( int i=0;i<ncGroupsAndCodesL.size();i++ ){
            NCGroupAndCodesSummary ncGroupAndCodes = ncGroupsAndCodesL.get(i);
            List<ValidNCCodeSummary> ncCodeL = ncGroupAndCodes.getNcCodes();
            for( int j=0;j<ncCodeL.size();j++){
                ValidNCCodeSummary ncCodeSummary = ncCodeL.get(j);
                DefeRecodesOfWorkInProc defeRecodesOfWorkInProcIns = new DefeRecodesOfWorkInProc();
                defeRecodesOfWorkInProcIns.setDefectCode(ncCodeSummary.getName());
                defeRecodesOfWorkInProcIns.setDefectDesc(ncCodeSummary.getDescription());
                result.add(defeRecodesOfWorkInProcIns);
            }
        }
        return AjaxResult.success(result);
    }

    /**
     * (在制不良录入)通过设备和工序查询：生产批、产品、单位
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getSfcBatch")
    public AjaxResult getSfcBatch(DefeRecodesOfWorkInProc defeRecodesOfWorkInProc){
        ArrayList<DefeRecodesOfWorkInProc> result = new ArrayList<DefeRecodesOfWorkInProc>();
        String site = CommonMethods.getSite();
        //----------------本地测试数据Start-----------------------------------------------------------------------------------------------
        List<SfcInWorkDto> sfcInWorkDtoList;
        try {
            sfcInWorkDtoList = sfcExService.listSfcInWork(site, defeRecodesOfWorkInProc.getResource(), defeRecodesOfWorkInProc.getOperation(), "");
        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        //---------------------------------------------------------------------------------------------------------------
        for(int i=0;i<sfcInWorkDtoList.size();i++){
            DefeRecodesOfWorkInProc ins = new DefeRecodesOfWorkInProc();
            SfcInWorkDto sfcInWorkDto = new SfcInWorkDto();
            sfcInWorkDto = sfcInWorkDtoList.get(i);
            String sfcBatch = sfcInWorkDto.getSfc();
            String product = sfcInWorkDto.getItem();
            String measUnit = sfcInWorkDto.getUnitOfMeasure();

            ins.setSfcBatch(sfcBatch);
            ins.setProduct(product);
            ins.setMeasUnit(measUnit);

            result.add(ins);
        }
        //-----------------获取当前资源下已判定报废批次-------------------------------------------------------------------
        DefeRecodesOfWorkInProc ins_condition = new DefeRecodesOfWorkInProc();
        ins_condition.setSite(defeRecodesOfWorkInProc.getSite());
        ins_condition.setResource(defeRecodesOfWorkInProc.getResource());
        ins_condition.setDetermineResult("报废");
        List<DefeRecodesOfWorkInProc> result_select = defeRecodesOfWorkInProcService.selectList(ins_condition);
        //--------------------------------------------------------------------------------------------------------------
        ArrayList<String> sfcBatch_L = new ArrayList<String>();
        for(int j=0;j<result_select.size();j++){
            DefeRecodesOfWorkInProc ins = result_select.get(j);
            sfcBatch_L.add(ins.getSfcBatch());
        }
        //-----------------循环排除已报废批次----------------------------------------------------------------------------
        if(sfcBatch_L.size()>0) {
            for (int k = 0; k < result.size(); k++) {
                DefeRecodesOfWorkInProc ins = result.get(k);
                if (sfcBatch_L.contains(ins.getSfcBatch())) {
                    result.remove(k);
                    k--;
                }
            }
        }
        //-----------------------------------------------------------------------------------------------------------
        return AjaxResult.success(result);
    }

    /**
     * （在制不良判定）查询：生产批次、产品、单位、不良代码、不良描述
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getSfcBatchForDetermine")
    public AjaxResult getSfcBatchForDetermine(DefeRecodesOfWorkInProc defeRecodesOfWorkInProc){
        List<DefeRecodesOfWorkInProc> result;
        try {
            EntityWrapper<DefeRecodesOfWorkInProc> entityWrapper = new EntityWrapper<>();
            entityWrapper.setEntity(defeRecodesOfWorkInProc);
            entityWrapper
                    .isNull(DefeRecodesOfWorkInProc.DETERMINE_RESULT)
                    .or().notIn(DefeRecodesOfWorkInProc.DETERMINE_RESULT,"报废");
            result = defeRecodesOfWorkInProcService.selectList(entityWrapper);
        } catch (Exception e) {
            logger.error("getSfcBatchForDetermine -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 在制不良录入保存和修改
     * @param defeRecodesOfWorkInProc  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/saveForEntry")
    public AjaxResult saveForEntry(@RequestBody DefeRecodesOfWorkInProc defeRecodesOfWorkInProc) {
        int count;
        try {
            String site = CommonMethods.getSite();
            String user = CommonMethods.getUser();
            Date nowTime = new Date();
            //------------------本地测试数据开始------------------------------------------------------------------------------------
            if(isLocalTest) {
                user = "mark";
            }
            //------------------本地测试数据结束------------------------------------------------------------------------------------
            List<DefeRecodesOfWorkInProc> unDetermineList;
            DefeRecodesOfWorkInProc conditionIns = new DefeRecodesOfWorkInProc();
            String operation = defeRecodesOfWorkInProc.getOperation();
            String sfcBatch = defeRecodesOfWorkInProc.getSfcBatch();
            conditionIns.setOperation(operation);
            conditionIns.setSfcBatch(sfcBatch);
            //------------------------------------------------------------------------------------------------------------
            EntityWrapper<DefeRecodesOfWorkInProc> entityWrapper = new EntityWrapper<>();
            entityWrapper.setEntity(conditionIns);
            entityWrapper.isNull(DefeRecodesOfWorkInProc.DETERMINE_RESULT);
            unDetermineList = defeRecodesOfWorkInProcService.selectList(entityWrapper);

            if( unDetermineList!=null && unDetermineList.size()>0 ){
                return AjaxResult.error( "该批次已录入不良信息，不可多次录入" );
            }else{
                String handle = StringUtils.createQUID();
                defeRecodesOfWorkInProc.setHandle(handle);
                defeRecodesOfWorkInProc.setSite(site);
                defeRecodesOfWorkInProc.setCreator(user);
                defeRecodesOfWorkInProc.setUpdater(user);
                defeRecodesOfWorkInProc.setCreatedDateTime(nowTime);
                defeRecodesOfWorkInProc.setModifiedDateTime(nowTime);
                count = defeRecodesOfWorkInProcService.insertOrUpdate(defeRecodesOfWorkInProc)? 1:0;
            }
        } catch (Exception e) {
            logger.error("DefeRecodesOfWorkInProc-saveForEntry -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : defeRecodesOfWorkInProc);
    }

    /**
     * 在制不良判定保存和修改
     * @param defeRecodesOfWorkInProc  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/saveForDetermine")
    public AjaxResult saveForDetermine(@RequestBody DefeRecodesOfWorkInProc defeRecodesOfWorkInProc) {
        int count;
        try {
            String site = CommonMethods.getSite();
            String user = CommonMethods.getUser();
            Date nowTime = new Date();
            //------------------本地测试数据开始------------------------------------------------------------------------------------
            if(isLocalTest) {
                user = "mark";
            }
            //------------------本地测试数据结束------------------------------------------------------------------------------------
            defeRecodesOfWorkInProc.setSite(site);
            defeRecodesOfWorkInProc.setUpdater(user);
            defeRecodesOfWorkInProc.setModifiedDateTime(nowTime);
            DefeRecodesOfWorkInProc oldIns = defeRecodesOfWorkInProcService.selectByHandle(defeRecodesOfWorkInProc.getHandle());
            if( oldIns.getDetermineResult()!=null && !"".equalsIgnoreCase(oldIns.getDetermineResult())){
                return AjaxResult.error( "批次"+oldIns.getSfcBatch()+"没有需要判定的不良信息!" );
            }
            count = defeRecodesOfWorkInProcService.insertOrUpdate(defeRecodesOfWorkInProc)? 1:0;
        } catch (Exception e) {
            logger.error("DefeRecodesOfWorkInProc-saveForDetermine -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : defeRecodesOfWorkInProc);
    }
}